import { http, toast} from 'uview-plus'

import configs from '@/config/config.js'
import { getToken, removeToken } from '@/utils/token'

http.setConfig((config) => {
	config = configs
	return config
});
// 请求拦截
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
	console.log('a',11233)
	if (!config.custom.hideLoading) {
		uni.showLoading({
			title: '加载中',
			mask: true,
		});
	}
	config.header = {
		'Authorization': getToken() || ''
	}
	if (config.method == 'GET') {}
	else if (config.method == "POST") {}
	return config
})

// 响应拦截
http.interceptors.response.use((response) => {
	if (response.statusCode != 200) {
		uni.showToast({
			title: response.data.msg || '500',
			icon: 'none',
			duration: 2000
		})
	}
	if (response.data.code == 401) {
		removeToken()
		uni.redirectTo({
			url: '/pages/login/index'
		})
	}
	if (response.data.code != 200) {
		uni.showToast({
			title: response.data.msg || '500',
			icon: 'none',
			duration: 2000
		})
	}
	uni.hideLoading()
	return response;
}, (err) => {
	console.log(err)
	uni.hideLoading()
	// 对响应错误做点什么
	if (err.errMsg == 'request:fail timeout') {
		uni.showToast({
			title: '请求超时，请重试!',
			duration: 2000,
			icon: "none"
		});
	} else if (err.errMsg == 'request:fail') {
		uni.showToast({
			title: '网络异常,请重试',
			duration: 2000,
			icon: "none"
		});
	} else {
		uni.showToast({
			title: '网络异常,请重试',
			duration: 2000,
			icon: "none"
		});
	}
	return err
})

export default http;
